<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="所属班型" prop="spuId">
        <el-select v-model="formData.spuId" placeholder="请选择">
          <el-option
            v-for="item in spuSimpleList"
            :key="item.id"
            :label="item.spuName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="套餐名称" prop="skuName">
        <el-input v-model="formData.skuName" placeholder="请输入 SKU 名称" />
      </el-form-item>
      <el-form-item label="套餐图片" prop="picUrl">
        <upload-img v-model="formData.picUrl" />
      </el-form-item>
      <el-form-item label="销售价格(分)" prop="price">
        <el-input type="number" v-model="formData.price" placeholder="请输入套餐销售价" />
      </el-form-item>
      <el-form-item label="销售原价(分)" prop="originalPrice">
        <el-input v-model="formData.originalPrice" type="number" placeholder="请输入套餐原价" />
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input v-model="formData.stock" type="number" placeholder="请输入套餐库存" />
      </el-form-item>
      <el-form-item label="库存预警值" prop="warnStockLimit">
        <el-input
          v-model="formData.warnStockLimit"
          type="number"
          placeholder="请输入套餐预警库存"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="2">下架</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as SkuApi from '@/api/client-mall/product/sku'
import useFormData from '@/hooks/ec/useFormData'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const formRef = ref() // 表单 Ref

const { formData, formRules, resetFormData } = useFormData<{
  id: string | null
  spuId: string | null
  skuName: string | null
  price: number | null
  originalPrice: number | null
  picUrl: string
  stock: number
  warnStockLimit: number
  status: number
}>({
  id: {
    defaultValue: null
  },
  spuId: {
    defaultValue: null,
    rules: [{ required: true, message: '商品SPU不能为空', trigger: 'blur' }]
  },
  skuName: {
    defaultValue: null,
    rules: [{ required: true, message: '商品SKU名字不能为空', trigger: 'blur' }]
  },
  price: {
    defaultValue: null,
    rules: [{ required: true, message: '销售价格不能为空', trigger: 'blur' }]
  },
  originalPrice: {
    defaultValue: null
  },
  picUrl: {
    defaultValue: '',
    rules: [{ required: true, message: '商品图片不能为空', trigger: 'blur' }]
  },
  stock: {
    defaultValue: 999,
    rules: [{ required: true, message: '库存不能为空', trigger: 'blur' }]
  },
  warnStockLimit: {
    defaultValue: 0,
    rules: [{ required: true, message: '预警库存不能为空', trigger: 'blur' }]
  },
  status: {
    defaultValue: 1,
    rules: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
  }
})

// 商品列表
const spuSimpleList = ref<{ spuName: string; id: string }[]>([])

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SkuApi.get(id)
      console.log('测试', formData.value)
    } finally {
      formLoading.value = false
    }
  }

  // TODO: 加载商品列表
  spuSimpleList.value = [
    {
      spuName: '商品1',
      id: '1'
    },
    {
      spuName: '商品2',
      id: '2'
    }
  ]
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    console.log(formData.value)

    const data = formData.value as unknown as SkuApi.SkuVO
    if (formType.value === 'create') {
      await SkuApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await SkuApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  resetFormData()
  formRef.value?.resetFields()
}
</script>
